// pages/sign/up.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectMember: true,
    project_index: 0,
    project_name: '',
    category_index: 0,
    stage_index: 0,
    category_array: [],
    stage_array: [],
    project_array: [],
    project_id: '',
    category_id: '',
    stage_id: '',
    areaValue: '',
    suitValue: '',
    members: {},
    accpet_member: [],
    show_member: [],
    checkbox_users: [],
    checkbox_members: [],
    userinfo: {},
    projects: [],
    showSelsect: false,
    leaderId: '',
  },

  contains: function(arrObj, idObj) {
    let i = arrObj.length;
    while (i--) {
      if (parseInt(arrObj[i]) == idObj) {
        return true;
      }
    }
    return false;
  },

  onSubmit: function(event) {
    return false;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中',
    });
    //获取品类列表
    const that = this;
    wx.request({
      url: app.globalData.requestUrl + 'api/category/lists',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
      },
      success: function(res) {

        let category_ids = options.category_ids ? options.category_ids.split(",") : [], //可能是直接添加项目也可能是项目添加产品
          category_array = res.data.data.lists, //全部品类
          temp_category = [];
        for (let key in category_array) {
          let obj = category_array[key];
          if (!that.contains(category_ids, obj.id)) {
            temp_category.push(obj);
          }
        }
        // 执行成功
        that.setData({
          category_array: temp_category,
          category_id: temp_category[0]['id'],
          userinfo: wx.getStorageSync('user_info'),
          accpet_member: [wx.getStorageSync('user_info').id]
        })

      },
      fail: function() {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });
    //获取项目列表
    wx.request({
      url: app.globalData.requestUrl + 'api/project/all',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
      },
      success: function(res) {
        //寻找默认项目
        let temp_project_array = res.data.data.projects.data,
          temp_index = 0;
        for (let key of Object.keys(temp_project_array)) {

          if (temp_project_array[key].id == options.project_id) {
            temp_index = key
          }

        }

        // 执行成功
        that.setData({
          project_array: res.data.data.projects.data,
          project_index: temp_index,
          project_id: options.project_id ? options.project_id : '',
          project_name: options.project_id ? res.data.data.projects.data[temp_index].project_name : '请输入项目名称'

        })

      },
      fail: function() {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });


    //获取成员列表

    wx.request({
      url: app.globalData.requestUrl + 'api/user/lists',
      method: 'POST',
      data: {
        id: app.globalData.userToken,
      },
      success: function(ret) {
        let data = ret.data;
        //根据分类ID查询分类名称：
        var lists = data.data.lists;
        for (var i in lists) {
          var majorName = lists[i][0].major_info.major_name;
          lists[majorName] = lists[i];
          delete lists[i];
        };
        that.setData({
          members: lists
        });
      },
      fail: function(e) {
        wx.showLoading({
          title: '系统错误请稍后重试',
        });
      }
    })

    //获取阶段列表
    wx.request({
      url: app.globalData.requestUrl + 'api/stage/lists',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
      },
      success: function(ret) {
        wx.hideLoading();
        var data = ret.data;
        that.setData({
          stage_array: data.data.lists,
          stage_id: data.data.lists[0]['id'],
        });
      },
      fail: function(e) {
        wx.showLoading({
          title: '系统错误请稍后重试',
        });
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  //添加成员
  addMember: function() {
    const that = this;
    let users = that.data.accpet_member, //已添加用户的id 集合
      members = wx.getStorageSync('members'), //所有用户
      temp_members = [];
    for (let key in members) {
      let obj = members[key];
      if (!that.contains(users, obj.id)) {
        temp_members.push(obj);
      }
    }
    let results = {}; //用于存储没有选择的用户
    for (var i in temp_members) {
      let majorName = temp_members[i].major_info.major_name;
      if (typeof results[majorName] != 'undefined' && results[majorName].length > 0) {
        results[majorName].push(temp_members[i]); //当“某个专业”已经有用户，则push用户即可
      } else {
        results[majorName] = []; //如果没有“某个专业”的key,则创建一个空白数组
        results[majorName].push(temp_members[i]);
      }
    };
    that.setData({
      members: results,
      selectMember: false,
    })
    this.setData({

      selectMember: false

    })
  },
  //选择项目
  changProject: function(e) {

    //输入逻辑
    const that = this;
    //处理项目已有品类 
    wx.request({
      url: app.globalData.requestUrl + 'api/project/detail',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        project_id: that.data.project_array[e.detail.value]['id']
      },

      success: function(res) {

        let category_ids = [];
        wx.hideLoading();
        for (let value of res.data.data.project.products) {
          category_ids.push(value.category_id);
        }

        wx.setStorageSync('category_ids', category_ids);

        wx.request({
          url: app.globalData.requestUrl + 'api/category/lists',
          method: 'POST',
          data: {
            user_token: app.globalData.userToken,
          },
          success: function(res) {

            let category_ids = wx.getStorageSync('category_ids'),

              category_array = res.data.data.lists, //全部品类
              temp_category = [];
            for (let key in category_array) {
              let obj = category_array[key];
              if (!that.contains(category_ids, obj.id)) {
                temp_category.push(obj);
              }
            }
            // 执行成功
            that.setData({
              category_array: temp_category,
              category_id: temp_category[0]['id']
            })

          },
          fail: function() {

            wx.showToast({
              title: '系统错误请稍后重试',
              icon: 'none'
            });
          }
        });


      },
      fail: function() {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });

    that.setData({
      project_index: e.detail.value,
      project_id: that.data.project_array[e.detail.value]['id'],
      project_name: that.data.project_array[e.detail.value]['project_name']
    })

  },

  //选择品类
  changeCategory: function(e) {
    const that = this;
    that.setData({
      category_index: e.detail.value,
      category_id: that.data.category_array[e.detail.value]['id'],

    })
  },
  //选择阶段
  changStage: function(e) {
    const that = this;
    this.setData({
      stage_index: e.detail.value,
      stage_id: that.data.stage_array[e.detail.value]['id']
    })
  },
  //输入面积
  setArea: function(e) {
    const that = this;
    that.setData({
      areaValue: e.detail.value
    })
  },

  //输入套数
  setSuit: function(e) {
    const that = this;
    that.setData({
      suitValue: e.detail.value
    })
  },


  //复选框的的选择
  checkboxChange: function(e) {
    const that = this;
    let temp_users = that.data.checkbox_users,
      temp_members = that.data.checkbox_members,
      id = e.detail.value[0],
      storage_members = wx.getStorageSync('members');
    if (e.detail.value != false) {
      //     //勾选复选框
      if (!that.contains(temp_users, id)) {
        temp_users.push(parseInt(id));
        for (let key of Object.keys(storage_members)) {
          let obj = storage_members[key];
          if (obj.id == parseInt(id)) {
            temp_members.push(obj)
          }
        }
        this.setData({
          checkbox_users: temp_users,
          checkbox_members: temp_members
        })
      }

    } else {
      //去掉勾选 
      let users = that.data.checkbox_users,
        members = that.data.checkbox_members,
        id = e.currentTarget.id;

      if (that.contains(users, id)) {

        users = app.removeValue(users, id);
        for (let key in members) {
          if (members[key].id == id) {
            members.splice(key);
          }
        }
        that.setData({
          checkbox_users: users,
          checkbox_members: members

        })
      }

    }
  },


  //添加成员后确定
  sureMember: function(e) {

    let users = this.data.checkbox_users,
      members = this.data.checkbox_members;
    this.setData({
      accpet_member: users,
      show_member: members,
      selectMember: true
    })
  },
  //添加成员取消

  cancelMember: function() {
    this.setData({
      selectMember: true
    })
  },


  //移除成员信息
  removeMember: function(e) {
    let accpet_member = this.data.accpet_member,
      show_member = this.data.show_member,
      index = null;
    let temp_member = app.removeValue(accpet_member, e.currentTarget.id);
    for (let key of Object.keys(show_member)) {
      if (show_member[key].id == e.currentTarget.id) {
        index = key
      }
    }
    show_member.splice(index, 1);

    this.setData({
      accpet_member: temp_member,
      show_member: show_member
    })
  },


  //添加产品取消
  cancel: function() {
    wx.navigateBack({
      delta: 1
    })
  },

  //添加产品确定
  makeSure: function() {
    const that = this,
      project_id = that.data.project_id,
      project_name = that.data.project_name,
      category_id = that.data.category_id,
      stage_id = that.data.stage_id,
      area = that.data.areaValue === '' ? 0 : that.data.areaValue,
      tao = that.data.suitValue === '' ? 0 : that.data.suitValue,
      users = that.data.accpet_member,
      leaderId = that.data.leaderId;

    wx.showLoading({
      title: '加载中',
      duration: 20000
    });

    wx.request({
      url: app.globalData.requestUrl + 'api/project/create/product',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        project_id: project_id,
        project_name: project_name,
        category_id: category_id,
        stage_id: stage_id,
        area: area,
        tao: tao,
        users: users,
        leaderId: leaderId
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          wx.showToast({
            title: '创建成功',
            icon: 'none',
          });
          wx.redirectTo({
            url: '/pages/componet/category/category?product_id=' + res.data.data.id + '&project_id=' + res.data.data.project_id + '&category_id=' + res.data.data.category_id
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          });
        }

      },
      fail: function(e) {
        wx.showLoading({
          title: '系统错误请稍后重试',
        });
      }
    })
  },
  call: function(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.id
    })
  },
  onfoucs: function(e) {
    if (e.detail.value == '请输入项目名称') {
      this.setData({
        project_name: ''
      })
    }
  },
  onblur: function(e) {
    if (e.detail.value == '') {
      this.setData({
        project_name: '请输入项目名称',
        showSelsect: false
      })
    }
  },


  setProjectName: function(e) {
    const project_array = this.data.project_array;
    const that = this;
    //联想
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: app.globalData.requestUrl + 'api/project/all',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        keyword: e.detail.value
      },
      success: function(res) {
        wx.hideLoading()
        // 执行成功
        if (res.data.data.projects.data.length > 0) {
          that.setData({
            projects: res.data.data.projects.data,
            showSelsect: true
          })
        } else {
          that.setData({
            projects: [],
            showSelsect: false
          })
        }

      },
      fail: function() {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });


    let temp_array = {},
      project_id = '',
      value = e.detail.value.trim();

    project_array.forEach(function(value) {
      temp_array[value.id] = value.project_name
    });

    for (var key of Object.keys(temp_array)) {

      if (temp_array[key] == value) {
        project_id = key
      }
    }


    if (project_id != '') {

      //处理项目已有品类 
      wx.request({
        url: app.globalData.requestUrl + 'api/project/detail',
        method: 'POST',
        data: {
          user_token: app.globalData.userToken,
          project_id: project_id
        },

        success: function(res) {

          let category_ids = [];
          wx.hideLoading();
          for (let value of res.data.data.project.products) {
            category_ids.push(value.category_id);
          }

          wx.setStorageSync('category_ids', category_ids);

          wx.request({
            url: app.globalData.requestUrl + 'api/category/lists',
            method: 'POST',
            data: {
              user_token: app.globalData.userToken,
            },
            success: function(res) {

              let category_ids = wx.getStorageSync('category_ids'),

                category_array = res.data.data.lists, //全部品类
                temp_category = [];
              for (let key in category_array) {
                let obj = category_array[key];
                if (!that.contains(category_ids, obj.id)) {
                  temp_category.push(obj);
                }
              }
              // 执行成功
              that.setData({
                category_array: temp_category,
                category_id: temp_category[0]['id']
              })

            },
            fail: function() {

              wx.showToast({
                title: '系统错误请稍后重试',
                icon: 'none'
              });
            }
          });

        },
        fail: function() {

          wx.showToast({
            title: '系统错误请稍后重试',
            icon: 'none'
          });
        }
      });
    }

    that.setData({
      project_id: project_id,
      project_name: value
    })

  },


  sureClickProject: function(e) {
    const that = this;
    let project_name = e.currentTarget.dataset.text,
      project_id = e.currentTarget.id;

    wx.request({
      url: app.globalData.requestUrl + 'api/project/detail',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        project_id: project_id
      },

      success: function(res) {

        let category_ids = [];
        wx.hideLoading();
        for (let value of res.data.data.project.products) {
          category_ids.push(value.category_id);
        }

        wx.setStorageSync('category_ids', category_ids);

        wx.request({
          url: app.globalData.requestUrl + 'api/category/lists',
          method: 'POST',
          data: {
            user_token: app.globalData.userToken,
          },
          success: function(res) {

            let category_ids = wx.getStorageSync('category_ids'),

              category_array = res.data.data.lists, //全部品类
              temp_category = [];
            for (let key in category_array) {
              let obj = category_array[key];
              if (!that.contains(category_ids, obj.id)) {
                temp_category.push(obj);
              }
            }
            // 执行成功
            that.setData({
              category_array: temp_category,
              category_id: temp_category[0]['id']
            })

          },
          fail: function() {

            wx.showToast({
              title: '系统错误请稍后重试',
              icon: 'none'
            });
          }
        });

      },
      fail: function() {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });

    that.setData({
      project_id: project_id,
      project_name: project_name,
      showSelsect: false
    })

  },
  selectLeader: function(e) {
    const that = this;
    let leaderId = that.data.leaderId,
      show_member = that.data.show_member,
      choseId = e.currentTarget.id;

    let choseIndex = show_member.findIndex(member => member.id == e.currentTarget.id);

    let choseMember = show_member.find(member => member.id == e.currentTarget.id);

    show_member = show_member.map(item => {
      return item.chosed = false, item
    })

    choseMember.chosed = true;

    let member_woca = show_member.filter((item) => {
      return item.id != e.currentTarget.id ? true : false;
    })

    if (e.currentTarget.id == leaderId) {

      choseMember.chosed = false;
      choseId = '';
    }

    member_woca.unshift(choseMember);

    that.setData({
      show_member: member_woca,
      leaderId: choseId
    })
  }

})